package com.audaque.springboot.foshanupload.web.nosaveframeworklogin.interceptor;


import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.result.R;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//通过配置order()的值，值越小，优先级越高。不配默认是0
public class LoginResponseInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TransmittableThreadLocalCurrentUser current = TransmittableThreadLocalCurrentUser.getCurrentUser();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        if (current != null) {
            R r = R.ok();
            current.setPassword(null);
            r.setData(current);
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return true;
        } else {
            R r = new R();
            r.setSuccess(false);
            r.setStatus(ResultCodeEnum.LOGIN_FAILE.getStatus());
            r.setDescription(ResultCodeEnum.LOGIN_FAILE.getDescription());
            response.getWriter().write(JSONUtil.toJsonStr(r));
            return false;
        }

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        TransmittableThreadLocalCurrentUser.remove();
    }
}
